;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.ContractManage", [])
        .controller("ContractManageCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus) {
            $scope.markInfo = {
                allChecked: false,
                curRow: -1,
                allCheckedBill: false
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };

            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 200,
                curPage: 1
            };
            $scope.activeFlag = [false, false];
            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑",
                2: "自动新增",
            };

            $scope.stepList = {
                curStep: 0
            };
            
            $scope.selectedList = [];

            $scope.toolbarConfig = {};
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.condition = {};
            $scope.conditionBill = {};
            $scope.dataList = [];
            $scope.tableConfig = {
                scrollWidth: 1200,
                fixedWidth: 160,
                tableCol: [
                    {
                        type: 'operate',
                        name: "操作",
                        width: 120,
                        isShow: true,
                        isFixed: true,
                    },
                    {
                        name: "合同号",
                        dataField: "billNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                    },
                    {
                        name: "接收单位",
                        dataField: "supplierOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户名称",
                        dataField: "purchareOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "付款方式",
                        dataField: "payType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                ]
            };

            $scope.tableConfigBill = {
                scrollWidth: 800,
                fixedWidth: 40,
                tableCol: [
                    {
                        name: "采购申请单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 200,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "发运方式",
                        dataField: "sendType",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "采购级别",
                        dataField: "purchaseLevel",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "申请人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "申请公司",
                        dataField: "purchaseOrgName",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "申请时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                ]
            };

            $scope.tableConfigMaterial = {
                scrollWidth: 800,
                tableCol: [
                    {
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialsDesc",
                        width: 200,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "零件分类",
                        dataField: "materialsType",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "单位",
                        dataField: "unit",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "数量",
                        dataField: "qty",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        needInput: true,
                        inputType: 'qty'
                    },
                ]
            };

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/contract/export"),
                sectionParam: { ids: [] },
                allUrl: ybHttp.RequestUrl("device", "/contract/exportAll")
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    },
                    scrollLeftWidth: {
                        width: $scope.tableConfig.fixedWidth + "px"
                    },
                    billFixedWidth: {
                        left: $scope.tableConfigBill.fixedWidth + "px"
                    }
                };
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function viewDetail(item) {
                getDetail(item).then(function(data) {
                    if (!data) {
                        return;
                    }

                    $scope.detailInfo = data;

                    $scope.changeTab(2);
                })
            }

            function getDataList(curPage) {
                $scope.exportParam.sectionParam.ids = [];
                $scope.markInfo.allChecked = false;
                $scope.markInfo.curRow = -1;
                var service = "device";
                var reqUrl = "/contract/list";
                
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                    filters: angular.copy($scope.condition)
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                        item.isChecked = false;
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function (conditionName = 'condition') {
                $scope[conditionName] = {};
            };

            $scope.collectBillData = function(item) {
                const idx = $scope.selectedList.findIndex(s =>s.billId == item.billId);
                if (idx > -1) {
                    !item.isChecked && $scope.selectedList.splice(idx, 1);
                } else {
                    $scope.selectedList.push(item);
                }
            };
            $scope.getBillIds = function(item) {
                const idx = $scope.exportParam.sectionParam.ids.findIndex(s =>s == item.id);
                if (idx > -1) {
                    !item.isChecked && $scope.exportParam.sectionParam.ids.splice(idx, 1);
                } else {
                    $scope.exportParam.sectionParam.ids.push(item.id);
                }
            }

            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }

            $scope.selectAll = function (list, type, cbName) {
                for (var item of list) {
                    item.isChecked = $scope.markInfo["allChecked" + type||''];

                    if (cbName) {
                        $scope[cbName](item);
                    }
                }
            };

            $scope.selectSingle = function (item, list, type, cbName) {
                let val
                if (!item.isChecked) {
                    val = false;
                } else {
                    val = checkAll(list);
                }
                $scope.markInfo["allChecked" + type||''] = val;

                if (cbName) {
                    $scope[cbName](item);
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.markInfo = {
                    allChecked: false,
                    curRow: -1,
                    allCheckedBill: false
                };

                $scope.detailInfo = {
                    materialsList: []
                };
                $scope.selectedList = [];
                $scope.tabFlag = {};
                $scope.stepList.curStep = 0;
            }

            $scope.selMateriel = function (e) {
                if (!$scope.detailInfo.purchareOrgName) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.addData = function() {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];

                setDefaultData();
                $scope.stepList.curStep = 1;
                $scope.changeTab(1);
            };

            $scope.detailInfo = {
                materialsList: []
            };

            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/contract/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.editData = function(item) {
                getDetail(item).then(function(data) {
                    if (!data) {
                        return;
                    }

                    $scope.detailInfo = data;
                    if(!!$scope.detailInfo.payDate){
                     $scope.detailInfo.payDate = $filter("YbDate")($scope.detailInfo.payDate, 'yyyy-MM-dd HH:mm:ss');
                    }
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.stepList.curStep = 1;
                    $scope.changeTab(1);
                })
            };

            $scope.deleteData = function(item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/contract/remove";
                    ybHttp.Post(service, reqUrl, item).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };


            $scope.addDataAuto = function() {
                $scope.tabFlag.type = 2;
                $scope.tabFlag.name = tabFlag[2];
                getBillList(1);
                $scope.changeTab(1);
            };

            function getBillList(curPage) {
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.orderPageInfo.pageSize,
                    pageNum: $scope.orderPageInfo.curPage,
                    filters: {
                        billStatus: "2",
                        seller: true,
                        isContract: 0,
                        notDirect: 1,
                        purchaseToSaleFlag: null,
                        billTypeMode: '合同',
                        ...$scope.conditionBill
                    }
                };
                $scope.orderDataList = [];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    if (!resp.value) {
                        resp.value = { list: [] }
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.sendType = item.sendTypeChildId ? item.shippingMethod + "-" + item.sendTypeChildName : item.shippingMethod;
                        item.purchaseLevel = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                        item.createDateShow = $filter("YbDate")(item.createDate);
                    });
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            }

            $scope.searchBills = function(curpage) {
                getBillList(curpage);
            };

            $scope.prevStep = function () {
                $scope.stepList.curStep = 0;
            };

            $scope.nextStep = function () {
                if ($scope.selectedList.length == 0) {
                    ybWidget.ShowMessage('请选择单据！', MESG_TYPE.Error);
                    return;
                }
                if (Array.from(new Set($scope.selectedList.map(s => s.purchaseOrgName))).length > 1) {
                    ybWidget.ShowMessage('只能选择同一个客户的单据！', MESG_TYPE.Error);
                    return;
                }
                if ($scope.selectedList.length >= 10) {
                    ybWidget.ShowMessage('选择单据不能超过10个！', MESG_TYPE.Error);
                    return;
                }

                ybHttp.Post('device', '/purchaseRequest/itemByIds', $scope.selectedList.map(s => s.billId)).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    const mergeredMaterials = resp.value.materialsList.reduce((total, cur) => {
                        const obj = {
                            materialsNo: cur.materialsNo,
                            materialsDesc: cur.materialsDes,
                            materialsType: cur.materialsType,
                            unit: cur.unit,
                            qty: cur.qty,
                        };

                        if (!total[obj.materialsNo]) {
                            total[obj.materialsNo] = obj;
                        } else {
                            total[obj.materialsNo].qty += obj.qty;
                        }

                        return total;
                    }, {});

                    $scope.detailInfo.materialsList = Object.values(mergeredMaterials);

                    const xx = $scope.selectedList[0];
                    $scope.detailInfo.purchaseOrgId = xx.purchaseOrgId;
                    $scope.detailInfo.purchareOrgName = xx.purchaseOrgName;
                    setDefaultData();
                    $scope.stepList.curStep = 1;
                });
            };

            function setDefaultData() {
                $scope.detailInfo.purchaseIds = $scope.selectedList.map(s => s.billId);
                $scope.detailInfo.purchaseNos = $scope.selectedList.map(s => s.billNo).join(',');
                $scope.detailInfo.supplierOrgId = $scope.curOrgId;
                $scope.detailInfo.supplierOrgName = $scope.curOrg.companyName;
                $scope.detailInfo.createDate = new Date();
                $scope.detailInfo.createId = $scope.curUserId;
                $scope.detailInfo.createName = $scope.curUser.name;
            }

            $scope.selectDealer = function () {
                $scope.jckFlag = false;
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.purchaseOrgId = data.platOrgId;
                    $scope.detailInfo.purchareOrgName = data.companyName;
                })
            };

            $scope.selectDispatch = function () {
                var param = {
                    name: "调度员",
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.detailInfo.supplierOrgId, 
                    fuzzyFlag: '1',
                    defaultRoleName: undefined
                };
                
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.dispatcherName = data.name;
                    $scope.detailInfo.dispatcherId = data.userId;
                })
            };

            $scope.checkRequired = function (item, type) {
                if (!item[type] || item[type] == '0') {
                    item[type+"Err"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"Err"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"Err"]
            };

            $scope.showErrTip = function (item, type) {
                if (!!item[type+"Err"]) {
                    item[type+"ShowErr"] = true
                }
            };

            $scope.hideErrTip = function (item, type) {
                item[type+"ShowErr"] = false
            };

            $scope.delMateriel = function (index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.detailInfo.materialsList.splice(index, 1);
                });
            };

            function checkListValid() {
                var isValid = true;
                for (let item of $scope.detailInfo.materialsList) {
                    // 校验数量
                    if ($scope.checkRequired(item, 'qty')) {
                        isValid = false;
                        break;
                    }
                }
                return isValid;
            }

            $scope.saveData = UserContextService.Debounce(function (argu) {
                saveDataFunc(argu);
            }, 500);

            function saveDataFunc (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }

                if ($scope.detailInfo.materialsList.length == 0) {
                    ybWidget.ShowMessage('请选择零件！', MESG_TYPE.Error)
                    return;
                }
                
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }

                ybHttp.Post('device', '/contract/save', $scope.detailInfo).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                });
            }

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/contract/downloadMaterialExcel",
                    importReqService: "device",
                    importReqUrl: "/contract/importMaterial",
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        const idx = $scope.detailInfo.materialsList.findIndex(f => f.materialsNo == item.materialsNo)
                        if (idx > -1) {
                            $scope.detailInfo.materialsList.splice(idx, 1, item)
                        } else {
                            $scope.detailInfo.materialsList.push(item)
                        }
                    });
                });
            };

            $scope.printData = function(item) {
                var param = {
                    billId: [item.id],
                    printType: 'ContractAgreement',
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            (function () {
                $scope.setFixedWidth();
                getDataList();
            })();
        }])
    ;
})(window, window.angular);